package com.greenant.store.activity;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.LogUtil.log;
import com.greenant.store.R;
import com.greenant.store.bean.AntAVObject;
import com.greenant.store.bean.AntGoods;
import com.greenant.store.bean.GoodsInfo;
import com.greenant.store.utils.Bimp;
import com.greenant.store.view.LoadingDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import android.app.ActionBar;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class EditGoodsActivity extends Activity {

	private TextView tTitle;
	private ImageView iBack;
	private TextView iFinish;
	private ImageView ivImage;
	private Resources res;
	private EditText descripEditText;
	private EditText priceEditText;
	private EditText stockEditText;
	private EditText styleEditText;
	private EditText unitEditText;
	private EditText discountEditText;
	private Button shelfButton;
	private ImageLoadingListener animateFirstListener = new EditGoodsListener();
	private DisplayImageOptions options;
	private GoodsInfo goodsInfo;
	//private String goodsObjectId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_goods);
		
		options = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.good_default)
			.showImageForEmptyUri(R.drawable.good_default)
			.showImageOnFail(R.drawable.good_default)
			.cacheInMemory(true)
			.cacheOnDisk(true)
			.considerExifParams(true)
			.displayer(new RoundedBitmapDisplayer(20)).build();
		
		res=getResources();
		
	    goodsInfo = (GoodsInfo) getIntent().getSerializableExtra("goodsinfo");  

        //�Զ���ActionBar  
        final ActionBar actionBar = getActionBar();  
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);  
        actionBar.setCustomView(R.layout.actionbar);//�Զ���ActionBar����  
       
        iBack = (ImageView)findViewById(R.id.left_btn);
        iFinish = (TextView)findViewById(R.id.right_btn);
        tTitle = (TextView)findViewById(R.id.actionbar_title);
        descripEditText = (EditText)findViewById(R.id.ddesc);
        priceEditText = (EditText)findViewById(R.id.dEditPrice);
        stockEditText = (EditText)findViewById(R.id.dEditStock); 
        styleEditText = (EditText)findViewById(R.id.dEditStyle);
        unitEditText = (EditText)findViewById(R.id.dEditUnit);
        discountEditText = (EditText)findViewById(R.id.dEditDiscount);
        shelfButton = (Button)findViewById(R.id.button_down_shelf);
        ivImage = (ImageView)findViewById(R.id.iv_big);           
                    
        tTitle.setText(res.getText(R.string.title_activity_edit_goods));
        iFinish.setText(R.string.action_finish);
        if (goodsInfo.getUrl()!=null)
        {
        	ImageLoader.getInstance().displayImage(goodsInfo.getUrl(), ivImage, options, animateFirstListener);
        }
        descripEditText.setText(goodsInfo.getDesc());
        priceEditText.setText(goodsInfo.getPrice()+"");
        stockEditText.setText(goodsInfo.getStock()+"");
        styleEditText.setText(goodsInfo.getStyle());
        unitEditText.setText(goodsInfo.getUnit());
        discountEditText.setText(goodsInfo.getDiscount()+"");
        if (goodsInfo.getOnShelf()){
        	shelfButton.setText(this.getString(R.string.down_shelf));
        }
        else{
        	shelfButton.setText(this.getString(R.string.up_shelf));
        }
        
        shelfButton.setOnClickListener(new OnClickListener()
        {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Thread t = new Thread(downShelfTread);
                t.start();
			}
        	
        });
        iBack.setOnClickListener(new OnClickListener()
        {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
         	    finish();
			}
        	
        });
        
        iFinish.setOnClickListener(new OnClickListener()
        {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
															
				if (descripEditText.getText().toString().length()==0){
					Toast.makeText(EditGoodsActivity.this, 
							EditGoodsActivity.this.getResources().getString(
									R.string.description_tip) , 
									Toast.LENGTH_SHORT).show();
				}else 
				if (priceEditText.getText().toString().length()==0){
					Toast.makeText(EditGoodsActivity.this, 
							EditGoodsActivity.this.getResources().getString(
									R.string.price_tip) , 
									Toast.LENGTH_SHORT).show();
				}else
				if (stockEditText.getText().toString().length()==0){
					Toast.makeText(EditGoodsActivity.this, 
							EditGoodsActivity.this.getResources().getString(
									R.string.stoke_tip) , 
									Toast.LENGTH_SHORT).show();
				}
				else {
					Thread t = new Thread(newTread);
	                t.start();
					//upLoadGoods();
					finish();
				}
			}
        	
        });
        
    }
	private static class EditGoodsListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}
	private void downShelf() 
	{	
		AntGoods avGoods= new AntGoods();	
		
		AVQuery<AntGoods> query = new AVQuery<AntGoods>(AntAVObject.CLASS_AVGOODS);
					
		try {
			avGoods = query.get(goodsInfo.getId());
		} catch (AVException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (avGoods.getBoolean(AntGoods.ATTR_IS_ON_SHELF)){
			avGoods.setShelfState(false);         
		}else {
			avGoods.setShelfState(true);  
		}
        avGoods.setFetchWhenSave(true);
        avGoods.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
              if(e!=null){
                  //�ϴ�ʧ��
            	  log.d("ʧ��","goods upload error!");
            	  Toast.makeText(EditGoodsActivity.this, "��Ʒ����ʧ��!", Toast.LENGTH_SHORT).show();
              }else{
                  //�ϴ��ɹ�
            	  log.d("�ɹ�","goods upload success!");
            	  Toast.makeText(EditGoodsActivity.this, "��Ʒ���³ɹ�!", Toast.LENGTH_SHORT).show();
              }
            }
        });
	}
	private void upLoadGoods() 
	{
		int tmpInt = 0;
		float price = 0;
		float discount =0;
		
		AntGoods avGoods= new AntGoods();	
		
		AVQuery<AntGoods> query = new AVQuery<AntGoods>(AntAVObject.CLASS_AVGOODS);
					
		try {
			avGoods = query.get(goodsInfo.getId());
		} catch (AVException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String str=descripEditText.getText().toString();
        avGoods.setDescription(str);
        
        str=styleEditText.getText().toString();
        avGoods.setStyle(str);
        
        str=unitEditText.getText().toString();
        avGoods.setUnit(str);
        
        str =priceEditText.getText().toString();
        try{     
        	price =Float.parseFloat(str);              
    	}catch(Exception e)
    	{               
    		return;              
        }
        avGoods.setPrice(price);
        
        str =discountEditText.getText().toString();
        try{     
        	discount =Float.parseFloat(str);              
    	}catch(Exception e)
    	{               
    		return;              
        }
        avGoods.setDiscount(discount);
        
        str=stockEditText.getText().toString();
        try{     
        	tmpInt =Integer.parseInt(str);              
    	}catch(Exception e)
    	{           
    		log.e("stringת��int����","str="+str);
    		return;              
        }
        avGoods.setStock(tmpInt);                    
        avGoods.setFetchWhenSave(true);
        avGoods.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
              if(e!=null){
                  //�ϴ�ʧ��
            	  log.d("ʧ��","goods upload error!");
            	  Toast.makeText(EditGoodsActivity.this, "��Ʒ����ʧ��!", Toast.LENGTH_SHORT).show();
              }else{
                  //�ϴ��ɹ�
            	  log.d("�ɹ�","goods upload success!");
            	  Toast.makeText(EditGoodsActivity.this, "��Ʒ���³ɹ�!", Toast.LENGTH_SHORT).show();
              }
            }
        });
	}
	
	Runnable newTread = new Runnable() {
 
        @Override
        public void run() {
        	upLoadGoods();
        }
    };
    
    Runnable downShelfTread = new Runnable() {
    	 
        @Override
        public void run() {
        	downShelf();
        }
    };
}


